package net.raebiger.spreadsheetcat.preference;

import java.io.IOException;

import net.raebiger.spreadsheetcat.R;
import net.raebiger.spreadsheetcat.google.AuthenticateAccountAction;
import net.raebiger.spreadsheetcat.util.DialogUtil;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AccountManagerCallback;
import android.accounts.AccountManagerFuture;
import android.accounts.AuthenticatorException;
import android.accounts.OperationCanceledException;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.Button;
import android.widget.ListView;

public class UserSettingActivity extends PreferenceActivity implements
		SharedPreferences.OnSharedPreferenceChangeListener {
	private final String AUTH_TOKEN_TYPE = "oauth2:https://spreadsheets.google.com/feeds";

	private AccountPreferences accountPreferences = null;
	private SpreadsheetPreferences spreadsheetPreferences = null;
	private volatile String authToken;

	@Override
	@SuppressWarnings("deprecation")
	// we need that to support Android 2.3
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		addPreferencesFromResource(R.xml.settings);

		PreferenceManager.getDefaultSharedPreferences(this).registerOnSharedPreferenceChangeListener(this);

		accountPreferences = new AccountPreferences(this);
		spreadsheetPreferences = new SpreadsheetPreferences(this, accountPreferences);
		getAuthToken(accountPreferences);

		accountPreferences.fillGoogleAccounts();
		addButtonTestAuthentication();

	}

	@SuppressWarnings("deprecation")
	private void getAuthToken(AccountPreferences accountPreferences) {
		AccountManager accountManager = AccountManager.get(this);
		accountManager.invalidateAuthToken(AUTH_TOKEN_TYPE, authToken);
		Account account = accountPreferences.getStoredGoogleAccountOrNull();

		authToken = null;
		accountManager.getAuthToken(account, AUTH_TOKEN_TYPE, false, new AccountManagerCallback<Bundle>() {

			@Override
			public void run(AccountManagerFuture<Bundle> future) {
				try {
					authToken = future.getResult().getString(AccountManager.KEY_AUTHTOKEN);
				} catch (OperationCanceledException e) {
					DialogUtil.getInstance().showDialog(R.string.pref_testAccountButtonCaption,
							UserSettingActivity.this);
				} catch (AuthenticatorException e) {
					DialogUtil.getInstance().showDialog(R.string.pref_testAccountButtonCaption,
							UserSettingActivity.this);
				} catch (IOException e) {
					DialogUtil.getInstance().showDialog(R.string.pref_testAccountButtonCaption,
							UserSettingActivity.this);
				}

				if (authToken == null) {
					Log.i("SSC", "Authentication failed.");
					disableAllPrefsExceptAccountSelection();

				} else {
					Log.i("SSC", "Authentication successful.");
					enablePrefs();
				}
			}
		}, null);

	}

	private void enablePrefs() {
		spreadsheetPreferences.enablePref(authToken);
	}

	private void disableAllPrefsExceptAccountSelection() {
		spreadsheetPreferences.disablePref();
	}

	@Override
	public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
		Log.i("SSC", accountPreferences.getStoredGoogleAccountnameOrNull());
		if (AccountPreferences.PREF_USERNAME.equals(key)) {
			getAuthToken(accountPreferences);
		} else if (SpreadsheetPreferences.PREF_SPREADSHEET.equals(key)) {
			spreadsheetPreferences.updatePrefSpeadsheetSummary(authToken);
			spreadsheetPreferences.readSelectedSpreadsheet(authToken);
		}
	}

	private void addButtonTestAuthentication() {
		ListView view = getListView();
		Button testAccountButton = new Button(this);
		testAccountButton.setText(getString(R.string.pref_testAccountButtonCaption));
		AuthenticateAccountAction authenticateAccountAction = new AuthenticateAccountAction(this);
		testAccountButton.setOnClickListener(authenticateAccountAction);
		view.addHeaderView(testAccountButton);
	}

	public Account getStoredGoogleAccountOrNull() {
		return accountPreferences.getStoredGoogleAccountOrNull();
	}
}